<template>
  <div>
    <el-upload
      :action="uploadImgUrl"
      :limit="1"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      accept="video/*"
      :headers="headers"
    >
      <el-button slot="trigger" type="primary" plain>选择视频</el-button>
      <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      的视频

      <el-button
        type="primary"
        link
        @click="dialogVisible = true"
        v-if="previewBtn"
      >
        预览视频
      </el-button>
    </div>
    <!-- 预览 -->
    <el-dialog
      v-model="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <video v-if="videoUrl" :src="videoUrl" controls></video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import {defineProps, defineEmits} from "vue"
const emit = defineEmits();
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
});

const showTip = computed(() => props.isShowTip && props.fileSize);
const { proxy } = getCurrentInstance();
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const dialogVisible = ref(false);
const previewBtn = ref(false);
const videoUrl = ref(null);

// 文件被上传之前被调用的方法
const beforeUpload = (file) => {
  const isLt100M = file.size / 1024 / 1024 < props.fileSize;
  if (!isLt100M) {
    proxy.$modal.msgError("上传视频大小不能超过5MB！");
  }
  return isLt100M;
};

// 上传成功
const handleSuccess = (response, file, fileList) => {
  previewBtn.value = true;
  videoUrl.value = response.url;
  emit("update:modelValue", response.fileName);
};

// 上传失败
const handleError = (err, file, fileList) => {
  proxy.$modal.msgError("视频上传失败！");
};

// 删除文件时发生的
const handleRemove = (file, fileList) => {
  previewBtn.value = false;
  videoUrl.value = null;
};
</script>

<style scoped>
.el-upload__tip {
  margin-left: 10px;
}
</style>
